package com.hellogood.yaohuo.client.common;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.yaohuo.shared.entity.Vendor;
import com.hellogood.yaohuo.shared.services.VendorService;
import com.smartgwt.client.types.Positioning;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;

public class VendorTextItemTreeClickHandler implements KeyPressHandler {
	private TextItem vendorItem = null;
	private TextItem selectItem = null;

	public VendorTextItemTreeClickHandler(TextItem vendorItem, TextItem selectItem) {
		this.vendorItem = vendorItem;
		this.selectItem = selectItem;
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		if (event.getKeyName().equals("Enter")) {
			Object vendor = vendorItem.getValue();
			if (vendor != null && !vendor.equals("")) {
				if (vendor.toString().contains("-")) {
					selectItem.focusInItem();
				} else {
					VendorService.Util.getInstance().getVendorByCode(vendor.toString(), new AsyncCallback<Vendor>() {

						@Override
						public void onSuccess(Vendor result) {
							if (result != null) {
								vendorItem.setValue(result.getVendorCode() + "-" + result.getVendorName());
							} else {
								VendorTreeWindow window = VendorTreeWindow.getInstance();
								window.updateSearchKey(vendorItem, selectItem);
								window.setPosition(Positioning.RELATIVE);
								window.setSize("500", "500");
								window.centerInPage();
								window.setTitle("供应商");
								window.show();
								window.getTreeGrid().focus();
							}
						}

						@Override
						public void onFailure(Throwable caught) {
							SC.say(caught.getMessage());

						}
					});

				}
			} else {
				VendorTreeWindow window = VendorTreeWindow.getInstance();
				window.updateSearchKey(vendorItem, selectItem);
				window.setPosition(Positioning.RELATIVE);
				window.setSize("500", "500");
				window.centerInPage();
				window.setTitle("请选择供应商");
				window.show();
				window.getTreeGrid().focus();
			}

		}

	}

}
